package javase.ch02.state;

import java.util.concurrent.TimeUnit;

/**
 * @Desc TODO
 * @Author chenmin
 * @Date 2025/10/30
 *
 * 线程状态转换
 * NEW        新建状态
 * RUNNABLE   可运行状态
 * TIMED_WAITING  计时等待状态
 * WAITING    等待状态
 * TERMINATED 终止状态
 * BLOCKED    阻塞状态
 */
public class ThreadStateDemo {

    public static void main(String[] args) {
        Thread t = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName());
        } , "t线程");
        System.out.println("线程新建状态 = "+t.getState());

        t.start();
        System.out.println("线程可运行状态 = "+t.getState());

        //主线程进入沉睡，从而确保t线程能够先执行
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("线程计时等待状态 = "+t.getState());

        //主线程必须等到t线程执行结束才可以结束
        try {
            t.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("线程终止状态 = "+t.getState());
    }

}
